package com.checkoutcheckins.server.auth;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;

@SuppressWarnings("serial")
public class OAuthVerified extends HttpServlet {

	private static final Logger logger = Logger.getLogger("checkoutcheckins");

	public void doGet(HttpServletRequest req, HttpServletResponse resp) {

		logger.info("Retrieving session and requestToken");
		HttpSession hs = req.getSession();

		CheckoutCheckinsOAuth oauth = new CheckoutCheckinsOAuth();

		// get previously established request token
		OAuthConsumer consumer = (OAuthConsumer) hs
				.getAttribute("requestToken");

		String retrievedToken = req.getParameter("oauthtoken_token");

		try {

			oauth.getProvider().retrieveAccessToken(consumer, retrievedToken);

			logger.info("Creating accessToken");

			// create cookies

			// TODO uncomment
			Cookie tokenCookie = new Cookie("4sqtoken", consumer.getToken());
			tokenCookie.setMaxAge(604800);

			resp.addCookie(tokenCookie);

			Cookie secretCookie = new Cookie("4sqsecret", consumer
					.getTokenSecret());
			secretCookie.setMaxAge(604800);

			resp.addCookie(secretCookie);
			logger.info("Created cookies for access token");

			logger.info("Forwarding to main checkoutcheckins page");
			resp.sendRedirect("/");

		} catch (OAuthMessageSignerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
